package com.kaili.client.service.Impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.kaili.client.service.ISubEwbGenerator;
import com.kaili.pojo.entity.BaseBarcodeRule;
import com.kaili.db.service.IBaseBarcodeRuleService;
import com.kaili.common.exception.BaseExcept;
import com.kaili.except.ResponseStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * package name:com.kaili.client.service.Impl
 * author:hasee
 * date :2018/6/5
 * project:micro-service
 */
@Service
public class SubEwbGenerator implements ISubEwbGenerator {
    @Autowired
    IBaseBarcodeRuleService ruleService;

    /**
     * 生成子单号接口
     *
     * @param ewb  主单号
     * @param size 子单数
     * @return 子单列表
     */
    @Override
    public List<String> getSubEwb(String ewb, int size) {
        Wrapper<BaseBarcodeRule> wrapper = new EntityWrapper<>();
        wrapper.where("ewb_type={0} and rdstatus={1}", 71,1);
        List<BaseBarcodeRule> lists = ruleService.selectList(wrapper);
        if (lists != null && lists.size() > 0) {
            BaseBarcodeRule rule = lists.get(0);
            int subLen = rule.getLength() - ewb.length();
            if (subLen <= 0) {
                throw new BaseExcept(ResponseStatus.SUB_EWB_GEN_LEN_ERR);
            }
            int subMaxSize = (int) (Math.pow(10, subLen) - 1);
            if (size > subMaxSize) {
                throw new BaseExcept(ResponseStatus.SUB_EWB_GEN_SIZE_ERR);
            }
            List<String> subEwb = new ArrayList<>();
            String format = "%0" + subLen + "d";
            for (int i = 0; i < size; i++) {
                subEwb.add(ewb + String.format(format, (1 + i)));
            }
            return subEwb;
        }
        throw new BaseExcept(ResponseStatus.SUB_EWB_GEN_NULL_ERR);
    }
}
